package com.clwl.supervise.superviseapp.service.sampling;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.request.AddSamplingCompany;
import com.clwl.supervise.superviseapp.entity.request.PushCompanyHistory;
import com.clwl.supervise.superviseapp.entity.request.SamplingCompany;
import com.clwl.supervise.superviseapp.entity.supervise.JgSamplingCompany;
import com.clwl.supervise.superviseapp.entity.supervise.JgSamplingFile;
import com.clwl.supervise.superviseapp.entity.supervise.JgSamplingPush;
import com.clwl.supervise.superviseapp.entity.vo.JgSamplingStatistics;
import com.clwl.supervise.superviseapp.entity.vo.TcCompanyVo;
import com.clwl.supervise.superviseapp.mapper.supervise.JgSamplingCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgSamplingFileMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgSamplingPushMapper;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Year;
import java.time.ZoneId;
import java.util.*;

@Service
public class JgSamplingService {
    @Resource
    private JgSamplingCompanyMapper companyMapper;
    @Resource
    private JgSamplingPushMapper pushMapper;
    @Resource
    private JgSamplingFileMapper fileMapper;

    /**
     * 抽检监管-查看企业列表
     *
     * @return list
     */
    public List<JgSamplingCompany> querySamplingCompanyList(SamplingCompany company) {
        Page<Map<String, Object>> iPage = Page.of(company.getPageNum(), company.getPageSize());
        //当前登录人信息
        TsUser userInfo = UserHelper.getUserInfo();
        Long deptId = userInfo.getDeptId() != null && userInfo.getDeptId() != 1 ? userInfo.getDeptId() : null;
        Page<JgSamplingCompany> page = companyMapper.queryPageCompanyPushList(iPage, deptId, company.getCompanyName(), company.getSupProcess(), company.getProcessCodeTwo(), company.getCheckStatus(), company.getClaimStatus(), company.getCancellationStatus(), company.getYear(), company.getStartTime(), company.getEndTime());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new ArrayList<>();
        }
        return page.getRecords();
    }

    /**
     * 查询抽检企业历史列表(分页)
     *
     * @param history 查询参数
     * @return
     */
    public List<TcCompanyVo> queryPagePushHistoryList(PushCompanyHistory history) {
        Page<Map<String, Object>> iPage = Page.of(history.getPageNum(), history.getPageSize());
        Page<TcCompanyVo> page = pushMapper.queryPushHistoryList(iPage, history.getCompanyId(), history.getSupProcess(), history.getProcessCodeTwo(), history.getCancellationStatus(), history.getCoverStatus(), history.getYear(), history.getStartTime(), history.getStartTime());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new ArrayList<>();
        } else {
            for (TcCompanyVo companyVo : page.getRecords()) {
                List<JgSamplingFile> jgSamplingFiles = fileMapper.querySamplingFileListByPushId(companyVo.getId());
                companyVo.setFileList(jgSamplingFiles);
            }
        }
        return page.getRecords();
    }

    /**
     * 查询抽检企业统计信息
     *
     * @param company
     * @return
     */
    public JgSamplingStatistics querySamplingStatistics(SamplingCompany company) {
        //当前登录人信息
        TsUser userInfo = UserHelper.getUserInfo();
        Long deptId = userInfo.getDeptId() != null && userInfo.getDeptId() != 1 ? userInfo.getDeptId() : null;
        return pushMapper.findSamplingStatistics(deptId, company.getCompanyName(), company.getSupProcess(), company.getProcessCodeTwo(), company.getClaimStatus(), company.getCheckStatus(), company.getCancellationStatus(), company.getCoverStatus(), company.getYear(), company.getStartTime(), company.getEndTime());

    }

    /**
     * 更新认领状态
     *
     * @param pushId      推送id
     * @param claimStatus 认领状态：0未认领、1已认领、2认领退回
     */
    public boolean updateClaimStatus(Long pushId, String claimStatus) {
        JgSamplingPush push = new JgSamplingPush();
        push.setId(pushId);
        if (claimStatus.equals("1")) {
            //获取当前登录人信息
            TsUser userInfo = UserHelper.getUserInfo();
            push.setClaimPersonnelId(userInfo.getId());
            push.setClaimPersonnelName(userInfo.getName());
        }
        push.setUpdateTime(new Date());
        push.setClaimStatus(claimStatus);
        push.setClaimStatus(claimStatus);
        int index = pushMapper.updateById(push);
        return index > 0;
    }

    /**
     * 回显企业推送信息
     *
     * @param pushId 企业推送ID
     * @return data
     */
    public TcCompanyVo queryPushCompany(Long pushId) {
        TcCompanyVo tcCompanyVo = pushMapper.queryPushCompanyByPushId(pushId);
        //根据推送ID查询企业推送文件信息
        List<JgSamplingFile> jgSamplingFiles = fileMapper.querySamplingFileListByPushId(pushId);
        if (jgSamplingFiles.size() > 0) {
            jgSamplingFiles.add(new JgSamplingFile());
            tcCompanyVo.setFileList(jgSamplingFiles);
            //验证上传允许状态：
            boolean result = findSamplingFileUploadNum(pushId);
            tcCompanyVo.setIsUpload(result ? 0 : 1);
        } else {
            jgSamplingFiles.add(new JgSamplingFile());
            tcCompanyVo.setFileList(jgSamplingFiles);
            tcCompanyVo.setIsUpload(0);
        }

        return tcCompanyVo;
    }


    public boolean findSamplingFileUploadNum(Long pushId) {
        //获取企业推送确认单数量以及日期
        List<JgSamplingFile> files = fileMapper.querySamplingFileListByPushId(pushId);
        if (files != null && files.size() > 0) {
            JgSamplingFile jgSamplingFile = files.get(0);
            return checkUploadDate(jgSamplingFile.getUploadDate());
        }
        return false;
    }

    /**
     * 验证文件上传日期的返回结果
     * 1.确认单首次上传后，需要间隔三个月后允许上传二次，比较系统时间是否大约上传日期的累加3个月后的时间，如果大约返回true:false
     * 2.确认单必须在当前12月31日之前上传完成，如果系统时间小于当年的12月31日返回true：false
     *
     * @param uploadDate true:false
     * @return
     */
    public boolean checkUploadDate(Date uploadDate) {
        Date date = new Date();
        // 创建一个Calendar实例并使用给定的Date对象初始化
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(uploadDate);
        // 将月份加上3个月
        calendar.add(Calendar.MONTH, 3);
        // 获取修改后的日期
        Date newDate = calendar.getTime();
        int comparisonResult = date.compareTo(newDate);

        // 获取当前年份
        int year = Year.now().getValue();
        // 使用LocalDate获取当年12月31日
        LocalDate localDate = LocalDate.of(year, 12, 31);
        // 转换为Date
        Date yearDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        //系统当前时间是否大于确认单上传后间隔三个月的日期，系统当前时间是否小于当年12月31日
        if (comparisonResult > 0 && date.compareTo(yearDate) < 0) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 上传确认单
     *
     * @param file
     * @return
     * @throws Exception
     */
    public FileResultEntity uploadSamplingFile(String file) throws Exception {
        return FileUploadUtil.uploadImageBase64Image(file, FileUploadEnum.flightPlan.getPath());
    }

    /**
     * 保存确认单信息
     *
     * @param company 保存参数
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveSamplingCompanyInfo(AddSamplingCompany company) throws Exception {
        TsUser userInfo = UserHelper.getUserInfo();
        if ("0".equals(company.getCancellationStatus()) && StringUtils.isNotEmpty(company.getFilePath())) {
            JgSamplingFile samplingFile = new JgSamplingFile();
            samplingFile.setSysFileId(0L);
            samplingFile.setSamplingPushId(company.getPushId());
            samplingFile.setJgSamplingFile(company.getFilePath());
            samplingFile.setFileName(company.getFileName());
//            samplingFile.setFileSize(new BigDecimal(size));
            samplingFile.setUploadDate(new Date());
            samplingFile.setCreateUserId(userInfo.getId());
            samplingFile.setCreateUserName(userInfo.getName());
            samplingFile.setSamplingPushId(company.getPushId());
            fileMapper.insert(samplingFile);
            updatePushCheckStatus(company.getPushId(), company.getCancellationStatus());
        } else {
            //更新上传状态和撤销状态
            JgSamplingPush push = new JgSamplingPush();
            push.setId(company.getPushId());
            push.setUploadStatus("1");
            push.setCancellationStatus(company.getCancellationStatus());
            pushMapper.updateById(push);
        }
    }

    /**
     * 确认单上传完成后，需要更新企业推送信息
     *
     * @param pushId             企业推送id
     * @param cancellationStatus 企业撤销状态
     */
    public void updatePushCheckStatus(Long pushId, String cancellationStatus) {
        //1.撤销状态值为正常的情况下，需要统计确认单数量，如果确认单文件数量为2，则更新企业覆盖状态为“1”已覆盖
        //2.撤销状态为撤销的情况下，则上传1次确认单时就直接更新企业覆盖状态为“1”已覆盖
        int index = fileMapper.queryCompanyViewFilesCountByPushId(pushId);
        if (index > 1 || cancellationStatus.equals("1")) {
            JgSamplingPush push = new JgSamplingPush();
            push.setId(pushId);
            push.setCoverStatus("1");
            push.setUploadStatus("1");
            push.setCancellationStatus(cancellationStatus);
            pushMapper.updateById(push);
        } else {
            //更新上传状态和撤销状态
            JgSamplingPush push = new JgSamplingPush();
            push.setId(pushId);
            push.setUploadStatus("1");
            push.setCancellationStatus(cancellationStatus);
            push.setCancellationStatus(cancellationStatus);
            pushMapper.updateById(push);
        }
    }

}
